package demo.springcloud.util;

import com.alibaba.fastjson.JSONObject;
import demo.springcloud.handle.DefaultListHandler;
import demo.springcloud.handle.DefaultSingleHandler;
import demo.springcloud.handle.ListHandler;
import demo.springcloud.handle.SingleHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用作微服务的 http 调用工具类。
 * 具体返回处理请按照实际项目返回结构来修改。
 *
 * @author yexi
 */
@Component
@Slf4j
public class MicroserviceUtils {

    @Resource
    private RestTemplate restTemplate;

    /**
     * 返回列表对象的 POST 请求
     *
     * @param url     带微服务名的url
     * @param request 请求体信息
     * @return null表示出现了请求的问题，需要日志排查。
     */
    public <T> List<T> doHttpPost(String url, JSONObject request, Class<T> clazz) {
        return this.doHttpPost(url, request, clazz, new DefaultListHandler());
    }

    public <T> List<T> doHttpPost(String url, JSONObject request, Class<T> clazz, ListHandler handler) {
        String returnMsg = this.doPost(url, request);
        return handler.handle(returnMsg, url, clazz);
    }

    /**
     * 返回单个对象的post请求
     */
    public <T> T doHttpPostRO(String url, JSONObject request, Class<T> clazz) {
        return this.doHttpPostRO(url, request, clazz, new DefaultSingleHandler());
    }

    public <T> T doHttpPostRO(String url, JSONObject request, Class<T> clazz, SingleHandler handler) {
        String returnMsg = this.doPost(url, request);
        return handler.handle(returnMsg, url, clazz);
    }

    public String doPost(String url, JSONObject request) {
        //请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(request, httpHeaders);
        String returnMsg;
        try {
            ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);
            returnMsg = response.getBody();
        } catch (Exception e) {
            log.error("远程调用微服务失败: " + url + "，本次远程调用停止，请排查原因", e);
            throw new RuntimeException("远程调用微服务失败: " + url + "，本次远程调用停止，请排查原因");
        }
        return returnMsg;
    }


}
